/**
 * Created by tums on 13/8/15.
 */
import AppDispatcher from './AppDispatcher.js';
import {EventEmitter} from 'events';

let CHANGE_EVENT = 'change';
let _todos = {};
let _filter = {
    id: null,
    text: null,
    complete: null
};

function create(text) {
    var id = (+new Date() + Math.floor(Math.random() * 999999)).toString(36);
    _todos[id] = {
        id: id,
        complete: false,
        text: text
    };
}

function destory(id) {
    delete _todos[id];
}

function complete(id) {
    _todos[id].complete = true;
}

function setFilter(id, text, complete) {
    Object.assign(_filter, {
        id: id,
        text: text,
        complete: complete
    });
}

let TodoStore = Object.assign({}, EventEmitter.prototype, {
    getAll: function () {
        var o = {};
        Object.keys(_todos).forEach(function (key) {
            if ((!_filter.id || _todos[key].id === _filter.id)
            && (!_filter.text || _todos[key].text === _filter.text)
            && (_filter.complete==null || _todos[key].complete === _filter.complete)) {
                o[key] = _todos[key];
            }
        });
        return o;
    },
    emitChange: function () {
        this.emit(CHANGE_EVENT);
    },
    addChangeListener: function (callback) {
        this.on(CHANGE_EVENT, callback);
    },
    removeChangeListener: function (callback) {
        this.removeChangeListener(CHANGE_EVENT, callback);
    },
    dispatcherIndex: AppDispatcher.register(function (payload) {
        let action = payload;
        let text;

        switch (action.actionType) {
            case 'CREATE':
                text = action.text.trim();
                if (text !== '') {
                    create(text);
                    TodoStore.emitChange();
                }
                break;
            case 'DESTORY':
                destory(action.id);
                TodoStore.emitChange();
                break;
            case 'COMPLETE':
                complete(action.id);
                TodoStore.emitChange();
                break;
            case 'FILTER':
                setFilter(action.id, action.text, action.complete);
                TodoStore.emitChange();
                break;
        }

        return true;
    })
});

export {TodoStore as default };